package routes

import (
	"context"
	"errors"
	"fmt"
	"net/http"

	"codeberg.org/vnpower/pixivfe/v2/core"
)

// isContextError checks if an error is due to context cancellation or deadline exceeded.
func isContextError(err error) bool {
	return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
}

// proxyHandler is a helper function that constructs and proxies a request.
func proxyHandler(w http.ResponseWriter, r *http.Request, baseURL string, headers map[string]string) error {
	targetURL := fmt.Sprintf("%s/%s", baseURL, r.URL.Path)

	req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, targetURL, nil)
	if err != nil {
		if isContextError(err) {
			return nil
		}
		return fmt.Errorf("failed to create request for %s: %w", baseURL, err)
	}

	for key, value := range headers {
		req.Header.Add(key, value)
	}

	if err := core.ProxyRequest(w, req); err != nil {
		if isContextError(err) {
			return nil
		}
		return fmt.Errorf("failed to proxy request to %s: %w", baseURL, err)
	}

	return nil
}

// SPximgProxy handles requests for static assets from s.pximg.net.
func SPximgProxy(w http.ResponseWriter, r *http.Request) error {
	return proxyHandler(w, r, "https://s.pximg.net", nil)
}

// IPximgProxy handles requests for image assets from i.pximg.net.
func IPximgProxy(w http.ResponseWriter, r *http.Request) error {
	headers := map[string]string{
		"Referer": "https://www.pixiv.net/",
	}
	return proxyHandler(w, r, "https://i.pximg.net", headers)
}

// UgoiraProxy handles requests for video assets from ugoira.com.
func UgoiraProxy(w http.ResponseWriter, r *http.Request) error {
	return proxyHandler(w, r, "https://ugoira.com/api/mp4", nil)
}
